// Copyright (c) 2024, the WwMusic project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

package com.springfairy.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class FileUploadController {

    @PostMapping("/uploadFile")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("文件为空");
        }

        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID() + suffix;

        String uploadPath = System.getProperty("user.dir") + "/uploads/";

        // 确保目录存在
        File dir = new File(uploadPath);
        if (!dir.exists()) {
            dir.mkdirs(); // 创建 uploads 目录
        }

        File dest = new File(uploadPath + newFileName);
        file.transferTo(dest); // 保存文件到硬盘


        String scheme = request.getScheme();             // http 或 https
        String serverName = request.getServerName();     // 域名或 IP
        int serverPort = request.getServerPort();        // 端口
        String contextPath = request.getContextPath();   // 应用路径

        String baseUrl = scheme + "://" + serverName + ":" + serverPort + contextPath + "/uploads/" + dest.getName();

        return ResponseEntity.ok(baseUrl);
    }

}

